<?php
/**
 * railbrowser
 *
 * PHP versions 5
 *
 * Copyright (C)
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
 * Fundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *
 * @author Bastian Schröder <bs@chemanet.de>
 * @version 2007-08-03
 * @package rail
 */

session_start();

require_once( 'railbrowser.conf.php' );
require_once( $cfg_pahToPHPrail . '/rail_connector.class.php' );
require_once( 'includes/derive_icon.php' );

define('RAILBROWSER_REVISION', '');
define('RAILBROWSER_VERSION', '1.1');

$rail = new rail_connector( $cfg_mysql_db, $cfg_mysql_user, $cfg_mysql_passwd, $cfg_mysql_host );
$rail->login($cfg_rail_user, $cfg_rail_passwd);

$smarty = new rail_smarty();
$smarty->caching = false;


/* ------------------------------------ Listener -------------------------------------- */
// update current object attributes
if( isset($_POST["attributes"]) ){
	$obj = rail_factory::get_object( $rail, $_SESSION['last_path'] );
	// get all attributes and check for changes
	$attributes = $obj->get_all_attributes();
	$update_attributes = array();
	foreach( $_POST["attributes"] as $attribute=>$value ){
		if( $attributes[ $attribute ] != $value )
			$update_attributes[$attribute] = $value;
	}
	// update all attributes, not found in all attributes.
	if( count($update_attributes) > 0 ){
		$obj->set_attributes( $update_attributes );
		// update $_SESSION["last_path"] if name variable is change
		if( isset( $update_attributes[OBJ_NAME] ) )
			$_SESSION["last_path"] = $obj->get_path();
	}
}
// copy object
if( isset( $_REQUEST['copy_object'] ) && $_REQUEST['copy_object'] > 0 ){
	$_SESSION['RAILBROWSER_clipboard'] = $_REQUEST['copy_object'];
	if( isset($_SESSION['RAILBROWSER_clipboard_cut']) ) unset($_SESSION['RAILBROWSER_clipboard_cut']);
	if( isset($_SESSION['RAILBROWSER_clipboard_aslink']) ) unset($_SESSION['RAILBROWSER_clipboard_aslink']);
	header('Location: index.php');
}
// cut object
else if( isset( $_REQUEST['cut_object'] ) && $_REQUEST['cut_object'] > 0 ){
	$_SESSION['RAILBROWSER_clipboard'] = $_REQUEST['cut_object'];
	$_SESSION['RAILBROWSER_clipboard_cut'] = true;
	if( isset($_SESSION['RAILBROWSER_clipboard_aslink']) ) unset($_SESSION['RAILBROWSER_clipboard_aslink']);
	header('Location: index.php');
}
// delete attribute
else if( isset( $_REQUEST['delete_attribute'] ) && strlen( $_REQUEST['delete_attribute'] ) > 0 ){
	$obj = rail_factory::get_object( $rail, $_SESSION['last_path'] );
	$obj->remove_attribute( $_REQUEST['delete_attribute'] );
	header('Location: index.php');
	header('Location: index.php');
}
// delete object
else if( isset( $_REQUEST['delete_object'] ) && $_REQUEST['delete_object'] > 0 ){
	$obj = rail_factory::get_object( $rail, $_REQUEST['delete_object'] );
	if( $obj->get_id() == $_SESSION['last_path'] )
		$obj_environment = $obj->get_environment();
	$obj->delete();
	if( isset( $obj_environment ) ) $_SESSION['last_path'] = $obj_environment;

	header('Location: index.php');
}
// update documents content
else if( isset( $_REQUEST['document_content'] ) && count($_REQUEST['document_content']) > 0 ){
	$obj_current = rail_factory::get_object( $rail, $_SESSION['last_path'] );
	if( $obj_current instanceof rail_document )
		$obj_current->set_content( $_REQUEST['document_content'] );
	header('Location: index.php');
}
// insert from clipboard
else if( isset($_REQUEST['insert_object']) && isset($_SESSION['RAILBROWSER_clipboard']) ){
	$obj_current = rail_factory::get_object( $rail, $_SESSION['last_path'] );
	$obj = rail_factory::get_object( $rail, $_SESSION['RAILBROWSER_clipboard'] );
	if( isset($_SESSION['RAILBROWSER_clipboard_aslink']) ){
		rail_factory::create_link( $rail, $obj_current, $obj->get_name(), $obj );
		unset( $_SESSION['RAILBROWSER_clipboard_aslink'] );
	}
	else{
		if( isset( $_SESSION['RAILBROWSER_clipboard_cut'] ) ){
			try{
				$obj->move($obj_current);
			}
			catch( rail_exception $e){
				if( $e->getMessage() == 'can\'t move this object into own inventory' )
					print('<script type="text/javascript">alert("Das Objekt kann nicht, in sich selbst, verschoben werden.");location.href="index.php";</script>');
die();
				#print_r($e);

			}
		}
		else
			$copy = $obj->copy( $obj_current );
	}

	unset($_SESSION['RAILBROWSER_clipboard']);
	header('Location: index.php');
}
// link object
else if( isset( $_REQUEST['link_object'] ) && $_REQUEST['link_object'] > 0 ){
	$_SESSION['RAILBROWSER_clipboard'] = $_REQUEST['link_object'];
	$_SESSION['RAILBROWSER_clipboard_aslink'] = true;
	if( isset($_SESSION['RAILBROWSER_clipboard_cut']) ) unset($_SESSION['RAILBROWSER_clipboard_cut']);
	header('Location: index.php');
}
// remove documents content
else if( isset($_REQUEST['remove_documents_content']) ){
	$obj_current = rail_factory::get_object( $rail, $_SESSION['last_path'] );
	if( $obj_current instanceof rail_document )
		$obj_current->remove_content();
	header('Location: index.php');
}

/* ------------------------------ Finger current object ------------------------------- */
// get $object and $_SESSION["last_path"]
// $object is the object actual shown in browser. In session var is the last actual path
// transporting the opject to next page stored in session
try{
	if( isset($_SESSION['last_path']) ){
		$object = rail_factory::get_object( $rail, $_SESSION['last_path'] );
		// check wehater a new object is given per POST or GET
		if( isset($_REQUEST['object']) && $object->get_id() != $_REQUEST['object']  )
			$object = rail_factory::get_object( $rail, $_REQUEST['object'] );
		else if( isset($_REQUEST['path']) && $object->get_path() != $_REQUEST['path']  )
			$object = rail_factory::get_object( $rail, $_REQUEST['path' ] );
	}
	else
		$object = rail_factory::get_object( $rail, $rail->get_user()->get_id() );

}
catch( Exception $e ){
	// if the opject can't load. try to display $_SESSION["last_path"].
	try{
		$object = rail_factory::get_object( $rail, $_SESSION["last_path"] );
		echo '<script type="text/javascript">alert("Das Objekt existiert nicht oder der Link war ungültig.");</script>';
	}
	catch(Exception $e){
		$object = rail_factory::get_object( $rail, $rail->get_user()->get_id() );
	}
}

// store new last_path to session]
$_SESSION["last_path"] = $object->get_path();


/* -------------------------- Get attributes and inventory ---------------------------- */
if( $object->is_readable( $rail->get_user() ) ){

	// get all attribute
	$attributes = array();
	foreach( $object->get_all_attributes() as $attribute => $value ){
		$attributes[] = array(
			'name' => $attribute,
			'value' => $value,

			"removeable" => ( !$object->is_attribute_protected( $attribute ) && $attribute != OBJ_NAME ),
			"readonly" => ( $object->is_attribute_protected( $attribute ) ),
		);
	}
	$smarty->assign( array(
		'attributes' => $attributes,
		'attributes_size' => count($attributes)
	));


	// get inventory
	$obj_inventory = array();
		foreach( $object->get_inventory() as $inventory ){
		$obj_inventory[] = array(
			'is_readable' => $inventory->is_readable( $rail->get_user() ),
			'is_writeable' => $inventory->is_writeable( $rail->get_user() ),
			'type' => get_class( $inventory ),
			'id' => $inventory->get_id(),
			'name' => $inventory->get_name(),
			'icon' => derive_icon( $rail, $inventory )
		);
	}
	$smarty->assign( array(
		'inventory' => $obj_inventory,
		'inventory_size' => count($obj_inventory)
	));
}


/* --------------------------------- Current object ----------------------------------- */
$smarty->assign( array(
	'object' => array(
		'is_readable' => $object->is_readable( $rail->get_user() ),
		'is_writeable' => $object->is_writeable( $rail->get_user() ),
		'type' => get_class( $object ),
		'environment' => ( $object instanceof rail_root ? 0 : $object->get_environment()->get_id() ),
		'id' => $object->get_id(),
		'name' => $object->get_name(),
		'path' => $object->get_path(),
		'icon' => derive_icon( $rail, $object ),
		'content' => $object instanceof rail_document ? derive_content( $rail, $object ) : false
	)
));


/* -------------------------------------- Display ------------------------------------- */
$smarty->assign( array(
	'clipboard' => 	isset($_SESSION['RAILBROWSER_clipboard']) ? array(
						'object' => $_SESSION['RAILBROWSER_clipboard'],
						'cut' => isset($_SESSION['RAILBROWSER_clipboard_cut']),
						'aslink' => isset($_SESSION['RAILBROWSER_clipboard_aslink'])
					) : false
));
$smarty->display( 'railbrowser.tpl' );


/* ------------------------------------ Functions ------------------------------------- */
/**
 * Derive the content from a rail_document for output in railadmin.
 *
 * @param rail_connector $pRailConnector
 * @param rail_document $pRailDocument
 * @return string HTML
 */
function derive_content( $pRailConnector, $pRailDocument ) {
	if( !$pRailDocument->is_readable( $pRailConnector->get_user() ) )
		return '<img src="css/img/document_closed.png" border="0" />';
	else if( !$pRailDocument->is_content_set() ){
		return '<button type="button" onclick="javascript:popup_init(\'Datei übertragen\', \'upload.php\', 420, 80);">Datei übertragen</button><img src="css/img/mime_empty.png" border="0" />';
	}

	$mimetype = $pRailDocument->get_mimetype();
	if( $mimetype == 'application/pdf' )
		$content = '<a target="_blank" href="get.php?object=' . $pRailDocument->get_id() . '&dl"><img src="css/img/pdf.png" border="0" />' . $pRailDocument->get_name() . '</a>';
	else if( substr( $mimetype, 0, 5 ) == 'text/' )
		$content = '<form action="index.php"><textarea name="document_content"' . ( !$pRailDocument->is_writeable( $pRailConnector->get_user() ) ? ' readonly="readonly"' : '' ) . '>' . $pRailDocument->get_content() . '</textarea>' . ($pRailDocument->is_writeable( $pRailConnector->get_user() ) ? '<button type="submit">Speichern</button></form>' : '');
	else if( substr( $mimetype, 0, 6 ) == 'image/' )
		$content =  '<img src="get.php?object=' . $pRailDocument->get_id() . '" border="0" />';
	else if( substr( $mimetype, 0, 6 ) == 'video/' )
		$content = '<a target="_blank" href="get.php?object=' . $pRailDocument->get_id() . '&dl"><img src="css/img/document_video.png" border="0" />' . $pRailDocument->get_name() . '</a>';
	else if( substr( $mimetype, 0, 6 ) == 'audio/' )
		$content = '<a target="_blank" href="get.php?object=' . $pRailDocument->get_id() . '&dl"><img src="css/img/document_audio.png" border="0" />' . $pRailDocument->get_name() . '</a>';
	else
		$content = '<a target="_blank" href="get.php?object=' . $pRailDocument->get_id() . '&dl"><img src="css/img/document.png" border="0" />' . $pRailDocument->get_name() . '</a>';


	return ($pRailDocument->is_writeable( $pRailConnector->get_user() ) ? '<button type="button" onclick="javascript:popup_init(\'Datei übertragen\', \'upload.php\', 420, 80);">Datei übertragen</button><button type="button" onclick="javascript:remove_documents_content();">Inhalt löschen</button>' : '') . $content;
}

?>